package com.mine.frame.mylandemo.ui.jiecang

import android.annotation.SuppressLint
import android.app.Service
import android.content.ComponentName
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.text.Editable
import android.text.method.DigitsKeyListener
import com.blankj.utilcode.util.ClickUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.ServiceUtils
import com.blankj.utilcode.util.SnackbarUtils
import com.mine.frame.common.base.BaseActivity
import com.mine.frame.common.empty.EmptyPresenter
import com.mine.frame.common.empty.IEmpty
import com.mine.frame.mylandemo.R
import com.mine.frame.mylandemo.ui.fgm.CommandFgm
import com.swallowsonny.convertextlibrary.toHexString
import com.third.device.mg.serialport.listener.MGNettyConnectListener
import com.third.device.mg.serialport.service.MGSocketService
import kotlinx.android.synthetic.main.atv_two.*

/**
 * @Date 2022/4/12
 * Description:E展厅2区 升降吊柜 和  平移导台
 */
class TwoDevControlAtv : BaseActivity<IEmpty, EmptyPresenter>(), IEmpty  , MGNettyConnectListener {

    private val leftFgm = CommandFgm()//升降吊柜
    private var ipLeft = "172.168.111.201"
    private var portLeft = 61233

    private val rightFgm = CommandFgm()//平移导台
    private var ipRight = "172.168.111.202"
    private var portRight  = 61233

    override fun initLayoutId(): Int = R.layout.atv_two

    override fun initPresenter(): EmptyPresenter = EmptyPresenter(this)

    private val serviceConnect: ServiceConnection by lazy {
        object : ServiceConnection {
            override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
                SnackbarUtils.with(edtLeftIP).setMessage("正在连接服务器...").showSuccess()
                MGSocketService.get().setListener(this@TwoDevControlAtv)
            }

            override fun onServiceDisconnected(name: ComponentName?) {
            }
        }
    }

    override fun initLayoutAfter(savedInstanceState: Bundle?) {
        val digits = "0123456789."
        edtLeftIP.keyListener = DigitsKeyListener.getInstance(digits)
        edtLeftIP.text = Editable.Factory.getInstance().newEditable(ipLeft)

        edtRightIP.keyListener = DigitsKeyListener.getInstance(digits)
        edtRightIP.text = Editable.Factory.getInstance().newEditable(ipRight)
        connectAndDisconnect()
        val ft =supportFragmentManager.beginTransaction()
        ft.replace(leftFml.id, leftFgm, "leftFgm")
        ft.replace(rightFml.id, rightFgm, "rightFgm")
        ft.commit()
    }



    /**
     * 连接和取消连接
     */
    private fun connectAndDisconnect() {
        ClickUtils.applySingleDebouncing(arrayOf(btnLeft, btnRight)) {
            when (it.id) {
                R.id.btnLeft -> {
                    KeyboardUtils.hideSoftInput(this)
                    if (edtLeftIP.text.isNullOrEmpty()) {
                        SnackbarUtils.with(edtLeftIP).setMessage("请输入IP地址").showWarning()
                        return@applySingleDebouncing
                    } else {
                        ipLeft = edtLeftIP.text.toString()
                    }

                    if (edtLeftPort.text.isNullOrEmpty()) {
                        SnackbarUtils.with(edtLeftIP).setMessage("请输入端口号").showWarning()
                        return@applySingleDebouncing
                    } else {
                        portLeft = edtLeftPort.text.toString().toInt()
                        if (portLeft < 1 || portLeft > 65535) {
                            SnackbarUtils.with(edtLeftIP).setMessage("端口号异常(1,65535)").showWarning()
                            return@applySingleDebouncing
                        }
                    }
                    if (ipLeft.isEmpty()) {
                        SnackbarUtils.with(edtLeftIP).setMessage("IP地址异常").showError()
                        return@applySingleDebouncing
                    }
                    MGSocketService.get().connectNetty(ipLeft, portLeft)
                }
                R.id.btnRight -> {
                    KeyboardUtils.hideSoftInput(this)
                    if (edtRightIP.text.isNullOrEmpty()) {
                        SnackbarUtils.with(edtRightIP).setMessage("请输入IP地址").showWarning()
                        return@applySingleDebouncing
                    } else {
                        ipRight = edtRightIP.text.toString()
                    }

                    if (edtRightPort.text.isNullOrEmpty()) {
                        SnackbarUtils.with(edtRightIP).setMessage("请输入端口号").showWarning()
                        return@applySingleDebouncing
                    } else {
                        portRight = edtRightPort.text.toString().toInt()
                        if (portRight < 1 || portRight > 65535) {
                            SnackbarUtils.with(edtRightIP).setMessage("端口号异常(1,65535)").showWarning()
                            return@applySingleDebouncing
                        }
                    }
                    if (ipRight.isEmpty()) {
                        SnackbarUtils.with(edtRightIP).setMessage("IP地址异常").showError()
                        return@applySingleDebouncing
                    }
                    MGSocketService.get().connectNetty(ipRight, portRight)
                }
            }
        }

    }
    override fun onStart() {
        super.onStart()
        if (!MGSocketService.get().isBind) {
            ServiceUtils.bindService(
                MGSocketService::class.java,
                serviceConnect,
                Service.BIND_AUTO_CREATE
            )
        }
    }
    override fun onDestroy() {
        if (MGSocketService.get().isBind) {
            ServiceUtils.unbindService(serviceConnect)
        }
        super.onDestroy()
    }


    /**
     * 更新指示器
     */
    private fun updateLeftIndicator(connect: Boolean) {
        val resId = if (connect) {
            R.drawable.blue_circle
        } else {
            R.drawable.red_circle
        }
        leftIndicator.setBackgroundResource(resId)
    }

    /**
     * 更新指示器
     */
    private fun updateRightIndicator(connect: Boolean) {
        val resId = if (connect) {
            R.drawable.blue_circle
        } else {
            R.drawable.red_circle
        }
        rightIndicator.setBackgroundResource(resId)
    }


    override fun connectBack(ip: String, port: Int) {
        if (ip == ipLeft && port == portLeft){
            updateLeftIndicator(true)
            leftFgm.onInitData(ip ,port ,0)
        }else{
            updateRightIndicator(true)
            rightFgm.onInitData(ip ,port ,1)
        }
    }

    override fun disconnectBack(ip: String, port: Int) {
        if (ip == ipLeft&& port == portLeft){
            updateLeftIndicator(false)
        }else{
            updateRightIndicator(false)
        }
    }

    @SuppressLint("SetTextI18n")
    override fun readBack(ip: String, port: Int, result: ByteArray) {
        SnackbarUtils.with(leftFml).setMessage("收到消息").showSuccess(true)
        tvInfo.text = "接收:${result.toHexString(true)}"
    }

    override fun writeBack(ip: String, port: Int, successful: Boolean, data: ByteArray) {
        if (successful){
            SnackbarUtils.with(leftFml).setMessage("发送成功").showSuccess(true)
        }else{
            SnackbarUtils.with(leftFml).setMessage("发送失败").showError(true)
        }

    }

    override fun errorBack(ip: String, port: Int, error: Throwable) {
        if (ip == ipLeft && port == portLeft){
            updateLeftIndicator(false)
        }else{
            updateRightIndicator(false)
        }
    }

}